﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace DotabuffWebAPI
{

    public class Query
    {
        public Query()
        {
            
        }

        public PlayerInfo GetPlayerInfo(string steamID)
        {
            PlayerInfo info = new PlayerInfo(steamID);

            //http://dotabuff.com/search?utf8=%E2%9C%93&q=sdfsdf
            try
            {
                string formatedURL = String.Format("http://dotabuff.com/search?q={0}", steamID);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(formatedURL);
                webRequest.Method = WebRequestMethods.Http.Get;

                var response = (HttpWebResponse)webRequest.GetResponse();

                string responseText;

                using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                {
                    responseText = streamReader.ReadToEnd();
                }

                // Vytáhneme data co chceme
                string winFilter = @"<span class=""won"">(\d+,?\d*)</span>";
                string lossFilter = @"<span class=""lost"">(\d+,?\d*)</span>";
                string wins;
                Match result = Regex.Match(responseText, winFilter);
                if (result.Success)
                {
                    string data = result.Groups[1].Value.Replace(",", "");
                    info.Wins =  Convert.ToInt32(data);
                }
                result = Regex.Match(responseText, lossFilter);
                if (result.Success)
                {
                    string data = result.Groups[1].Value.Replace(",", "");
                    info.Loss = Convert.ToInt32(data);
                }

            }
            catch (WebException webException)
            {
 
            }
            catch (SystemException systemException)
            {

            }

            return info;
        }
    }
}
